<template>
  <el-dialog
    title="选择工序"
    width="800px"
    append-to-body
    :close-on-click-modal="false"
    :visible.sync="visible"
    :close-on-press-escape="false"
    :show-close="false"
    @open="openHandler"
    @closed="closedHandler"
  >
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane v-for="(item, index) in data" :key="index" :label="`${item.label}（${item.selected.length}）`" :name="item.value">
        <el-scrollbar style="height: calc(70vh - 90px);font-size: 12px;">
          <el-tree
            :ref="'tree_' + item.value"
            :data="item.children"
            :props="checkTypeProps"
            node-key="value"
            highlight-current-row
            show-checkbox
            default-expand-all
            :default-checked-keys="item.selected"
            @check="checkHandler"
            @check-change="handleCheckChange"
          />
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>
    <div slot="footer" class="dialog-footer">
      <el-row type="flex" align="center">
        <el-col :span="12" style="text-align: left">
          <el-button type="primary" plain @click="selectAll">全选当前页</el-button>
          <el-button type="warning" plain @click="clear">清空当前页</el-button>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import { getCheckTableTree } from '@/api/common'
export default {
  name: 'SelectProcess',
  props: {
    visible: { type: Boolean, default: false },
    selected: { type: Array, default: () => [] },
    buildingId: { type: String, default: '' },
    containOld: { type: Boolean, default: false }
  },
  data() {
    return {
      data: [],
      activeName: '',
      checkTypeProps: {
        children: 'children',
        label: function(data, node) {
          return (data.seq ? data.seq + ' - ' : '') + data.label
        }
      }
    }
  },
  watch: {
    buildingId(val) {
      this.$emit('update:selected', [])
      this.getSpecialList(val, this.containOld)
    },
    containOld(val) {
      this.$emit('update:selected', [])
      this.getSpecialList(this.buildingId, val)
    }
  },
  created() {
    this.getSpecialList('', true)
  },
  methods: {

    /**
     * 查询专业类别列表
     */
    getSpecialList(buildingId = '', containOld = false) {
      if (buildingId) {
        this.data = []
      }
      getCheckTableTree({ buildingId, containOld }).then(response => {
        const data = response.data || []
        data.forEach(item => {
          item.selected = this.getIncludeCheckTableIds(item.children, this.selected)
        })
        this.data = data
        this.activeName = this.data[0].value
      })
    },
    /**
     * 树节点选中事件
     * @param data 节点数据
     * @param checkedNodes 勾选的节点
     * @param checkedKeys 勾选的节点key
     * @param halfCheckedNodes
     * @param halfCheckedKeys
     */
    checkHandler(data, { checkedNodes = [], checkedKeys = [], halfCheckedNodes = [], halfCheckedKeys = [] }) {
      // this.data.find(item => item.name === this.activeName).selected = checkedNodes.filter(item => !!item.cfchecktypeid).map(item => item.fid)
    },
    /**
     * 节点数据改变
     * @param data
     * @param checked
     * @param indeterminate
     */
    handleCheckChange(data, checked, indeterminate) {
      if (data.type === 'checkTable') {
        const id = data.value
        if (checked) {
          const tabData = this.data.find(item => item.value === this.activeName)
          const selected = tabData.selected
          const ids = this.getIncludeCheckTableIds(tabData.children, [id])
          if (ids.length > 0 && !selected.includes(ids[0])) {
            selected.push(ids[0])
          }
        } else {
          this.data.find(item => item.value === this.activeName).selected.splice(this.data.find(item => item.value === this.activeName).selected.indexOf(id), 1)
        }
      }
    },
    /**
     * 全选当前页
     */
    selectAll() {
      const tree = this.$refs['tree_' + this.activeName][0]
      const nodeKeys = this.data.find(item => item.value === this.activeName).children.map(item => item.value)
      const checkedKeys = tree.getCheckedNodes().filter(item => item.type === 'checkType').map(item => item.value)
      if (!(nodeKeys.length === checkedKeys.length && nodeKeys.every(item => checkedKeys.includes(item)))) {
        tree.setCheckedKeys(nodeKeys)
      }
    },
    /**
     * 清空当前页
     */
    clear() {
      this.$refs['tree_' + this.activeName][0].setCheckedNodes([])
    },
    /**
     * 确认选择
     */
    confirm() {
      const selected = []
      for (const item of this.data) {
        selected.push(...item.selected)
      }
      this.$emit('update:selected', selected)
      this.$emit('update:visible', false)
    },
    /**
     * 取消关闭dialog
     */
    cancel() {
      for (const item of this.data) {
        this.$refs['tree_' + item.value][0].setCheckedNodes([])
      }
      this.$emit('update:visible', false)
    },
    /**
     * 打开窗口前处理
     */
    openHandler() {
      if (this.data.length > 0) {
        for (const item of this.data) {
          item.selected = this.getIncludeCheckTableIds(item.children, this.selected)
        }
      }
    },
    /**
     * 关闭窗口前处理
     */
    closedHandler() {
      if (this.visible) {
        this.$emit('update:visible', false)
      }
      this.data.forEach(item => {
        item.selected = []
      })
    },
    /**
     * 获取已选择
     * @param checkTypes 分部分项数据
     * @param checkTableIds 工序ID集合
     * @return {*[]}
     */
    getIncludeCheckTableIds(checkTypes = [], checkTableIds = []) {
      const result = []
      for (const checkType of checkTypes) {
        if (checkType.children.length > 0) {
          const ids = checkType.children.filter(item => checkTableIds.includes(item.value)).map(item => item.value)
          result.push(...ids)
        }
      }
      return result
    }
  }
}
</script>

<style scoped>

</style>
